<?php

class SJB_Classifieds_AddListing extends SJB_Function
{
	public function isAccessible()
	{
		if ($this->getAclRoleID()) {
			$this->setPermissionLabel('subuser_add_listings');
		}
		return parent::isAccessible();
	}

	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();
		$error = null;

		$post_max_size_orig = ini_get("post_max_size");
		$session_maxlifetime = ini_get("session.gc_maxlifetime");
		$server_content_length = isset($_SERVER['CONTENT_LENGTH']) ? $_SERVER['CONTENT_LENGTH'] : null;
		$listingTypeID = SJB_Request::getVar('listing_type_id', false);
		$passed_parameters_via_uri = SJB_Request::getVar('passed_parameters_via_uri', false);
		$pageID = false;
		if ($passed_parameters_via_uri) {
			$passed_parameters_via_uri = SJB_UrlParamProvider::getParams();
			$listingTypeID = isset($passed_parameters_via_uri[0]) ? $passed_parameters_via_uri[0] : $listingTypeID;
			$pageID = isset($passed_parameters_via_uri[1]) ? $passed_parameters_via_uri[1] : false;
		}

		/**
		 * >>>>> for listing preview @author still
		 */



		$formSubmittedFromPreview = SJB_Request::getVar('action_add', false, 'POST') && SJB_Request::getVar('from-preview', false, 'POST');
		$editTempListing = SJB_Request::getVar('edit_temp_listing', false, 'POST');

		if ($formSubmittedFromPreview || $editTempListing) {
			$listingSID = SJB_Session::getValue('preview_listing_sid_for_add');
			$listing_info = SJB_ListingManager::getListingInfoBySID($listingSID);

			if (empty($listingTypeID) && !empty($listing_info)) {
				// if on preview page "POST" button was pressed
				$formSubmittedFromPreview = SJB_Request::getVar('action_add', false, 'POST') && SJB_Request::getVar('from-preview', false, 'POST');
				if ($formSubmittedFromPreview) {
					$listing = new SJB_Listing($listing_info, $listing_info['listing_type_sid']);
					$properties = $listing->getProperties();
					foreach ($properties as $fieldID => $property) {
						switch ($property->getType()) {
							case 'date':
								if (!empty($listing_info[$fieldID])){
									$listing_info[$fieldID] = SJB_I18N::getInstance()->getDate($listing_info[$fieldID] );
								}
								break;
							case 'complex':
								$complex = $property->type->complex;
								$complexProperties = $complex->getProperties();
								foreach ($complexProperties as $complexfieldID => $complexProperty) {
									if ($complexProperty->getType() == 'date') {
										$values = $complexProperty->getValue();
										foreach ($values as $index => $value) {
											if (!empty($listing_info[$fieldID][$complexfieldID][$index])) {
												$listing_info[$fieldID][$complexfieldID][$index] = SJB_I18N::getInstance()->getDate($listing_info[$fieldID][$complexfieldID][$index]);
											}
										}
									}
								}
								break;
						}
					}
				}
				if ($editTempListing || $formSubmittedFromPreview) {
					$current_user = SJB_UserManager::getCurrentUser();
					$listingTypeID = SJB_ListingTypeManager::getListingTypeIDBySID($listing_info['listing_type_sid']);

					// check wether user is owner of the temp listing
					if ($listing_info['user_sid'] != $current_user->getID()) {
						$error['NOT_OWNER_OF_LISTING'] = $listingSID;
					}

					// set listing info and listing type id
					$_REQUEST = array_merge($_REQUEST, $listing_info);
					$_REQUEST['listing_type_id'] = $listingTypeID;
				}
			}
			if (empty($listing_info)) {
				$listingSID = null;
				SJB_Session::unsetValue('preview_listing_sid_for_add');
			}
		} else {
			$listingSID = null;
			SJB_Session::unsetValue('preview_listing_sid_for_add');
		}
		// if preview button was pressed
		$isPreviewListingRequested = SJB_Request::getVar('preview_listing', false, 'POST');
		/*
		 * <<<<< for listing preview
		 */

		// get post_max_size in bytes
		$val = trim($post_max_size_orig);
		$tmp = substr($val, strlen($val) - 1);
		$tmp = strtolower($tmp);
		/*
		 * if ini value is K - then multiply to 1024
		 * if ini value is M - then multiply twice: in case 'm', and case 'k'
		 * if ini value is G - then multiply tree times: in 'g', 'm', 'k'
		 *
		 * out value - in bytes!
		 */
		switch ($tmp) {
			case 'g':
				$val *= 1024;
			case 'm':
				$val *= 1024;
			case 'k':
				$val *= 1024;
		}
		$post_max_size = $val;

		$filename = SJB_Request::getVar('filename', false);
		if ($filename) {
			$listing_id = SJB_Request::getVar('listing_id', '', 'default', 'int');
			$file = SJB_UploadFileManager::openFile($filename, $listing_id);
			$errors['NO_SUCH_FILE'] = true;
		}

		if (empty($_POST) && ($server_content_length > $post_max_size)) {
			$errors['MAX_FILE_SIZE_EXCEEDED'] = 1;
			$listing_id = SJB_Request::getVar('listing_id', null, 'GET', 'int');
			$tp->assign('post_max_size', $post_max_size_orig);
		}

		$tmp_listing_id_from_request = SJB_Request::getVar('listing_id', false, 'default', 'int');

		if ($productsInfo = SJB_ListingManager::canCurrentUserAddListing($error, $listingTypeID)) {

			$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listingTypeID);
			$current_user = SJB_UserManager::getCurrentUser();
			$pages = SJB_PostingPagesManager::getPagesByListingTypeSID($listing_type_sid);
			if (!empty($tmp_listing_id_from_request))
				$tmp_listing_sid = $tmp_listing_id_from_request;
			elseif (!$tmp_listing_id_from_request)
				$tmp_listing_sid = time();

			if (!$pageID)
				$pageID = $pages[0]['page_id'];

			$pageSID = SJB_PostingPagesManager::getPostingPageSIDByID($pageID, $listing_type_sid);
			$isPageLast = SJB_PostingPagesManager::isLastPageByID($pageSID, $listing_type_sid);
			$productSID = SJB_Request::getVar('product_sid', false, 'default', 'int');
			if ($productSID)
				$contract = new SJB_Contract(array('contract_id' => $productSID));
			elseif (count($productsInfo) == 1) {
				$productInfo = array_pop($productsInfo);
				$productSID = $productInfo['contract_id'];
				$contract = new SJB_Contract(array('contract_id' => $productSID));
			}
			else {
				$tp->assign('listing_id', $tmp_listing_sid);
				$tp->assign('products_info', $productsInfo);
				$tp->assign('listingTypeID', $listingTypeID);
				$tp->display('listing_product_choice.tpl');
			}

			if ($productSID) {
				$tp->assign("listing_id", $tmp_listing_sid);
				$extraInfo = $contract->extra_info;
				$numberOfPictures = isset($extraInfo['number_of_pictures']) ? $extraInfo['number_of_pictures'] : 0;
				$tp->assign("pic_limit", $numberOfPictures);
				$tp->assign("product_sid", $productSID);
				$listing_types_info = SJB_ListingTypeManager::getAllListingTypesInfo();
				if (!$listingTypeID && count($listing_types_info) == 1) {
					$listing_type_info = array_pop($listing_types_info);
					$listingTypeID = $listing_type_info['id'];
				}
			}

			if ($productSID && $listingTypeID) {
				$form_submitted = isset($_REQUEST['action_add']) || isset($_REQUEST['action_add_pictures']) || $isPreviewListingRequested;

				/*
				 * social plugin
				 * complete listing of data from an array of social data
				 * if is allowed
				 */
				$aAutoFillData = array('formSubmitted' => &$form_submitted, 'listingTypeID' => &$listingTypeID);
				SJB_Event::dispatch('SocialSynchronization', $aAutoFillData);
				/*
				 * end of "social plugin"
				 */

				$listing = new SJB_Listing($_REQUEST, $listing_type_sid, $pageSID);
				$listing->deleteProperty('featured');
				$listing->deleteProperty('priority');
				$listing->deleteProperty('status');
				$listing->deleteProperty('reject_reason');
				// delete special only JobG8 property
				$listing->deleteProperty('company_name');

				$access_type = $listing->getProperty('access_type');
				if ($form_submitted) {
					if (!empty($access_type)) {
						$listing->addProperty(
							array('id' => 'access_list',
								'type' => 'multilist',
								'value' => SJB_Request::getVar("list_emp_ids"),
								'is_system' => true));
					}
					$listing->addProperty(
						array('id' => 'contract_id',
							'type' => 'id',
							'value' => $productSID,
							'is_system' => true));

				}

				$screening_questionnaires = SJB_ScreeningQuestionnaires::getList($current_user->getSID());
				if (SJB_Acl::getInstance()->isAllowed('use_screening_questionnaires') && $screening_questionnaires) {
					$issetQuestionnairyField = $listing->getProperty('screening_questionnaire');
					if ($issetQuestionnairyField) {
						$value = SJB_Request::getVar("screening_questionnaire");
						$listing_info = $_REQUEST;
						$value = $value ? $value : isset($listing_info['screening_questionnaire']) ? $listing_info['screening_questionnaire'] : '';
						$listing->addProperty(
							array('id' => 'screening_questionnaire',
								'type' => 'list',
								'caption' => 'Screening Questionnaire',
								'value' => $value,
								'list_values' => SJB_ScreeningQuestionnaires::getListSIDsAndCaptions($current_user->getSID()),
								'is_system' => true));
					}
				}
				else {
					$listing->deleteProperty('screening_questionnaire');
				}
				/*
				 * social plugin
				 * "synchronization"
				 * if user is not registered using linkedin , delete linkedin sync property
				 * also if sync is turned off in admin part
				 */
				$aAutoFillData = array('oListing' => &$listing, 'userSID' => $current_user->getSID(), 'listingTypeID' => $listingTypeID, 'listing_info' => $_REQUEST);
				SJB_Event::dispatch('SocialSynchronizationFields', $aAutoFillData);
				/*
				 * end of social plugin "sync"
				 */

				$add_listing_form = new SJB_Form($listing);
				$add_listing_form->registerTags($tp);

				$field_errors = array();

				if ($form_submitted && ($formSubmittedFromPreview || $add_listing_form->isDataValid($field_errors))) {
					
					if ($isPageLast) {
						$listing->addProperty(
							array('id' => 'complete',
								'type' => 'integer',
								'value' => 1,
								'is_system' => true));
					}
					$listing->setUserSID($current_user->getSID());
					$extraInfo = $contract->extra_info;
					$listing->setProductInfo($extraInfo);

					if (empty($access_type->value))
						$listing->setPropertyValue('access_type', 'everyone');

					if ($current_user->isSubuser()) {
						$subuserInfo = $current_user->getSubuserInfo();
						$listing->addSubuserProperty($subuserInfo['sid']);
					}

					/**
					 * >>>>> listing preview @author still
					 */
					if (!empty($listingSID)) {
						$listing->setSID($listingSID);
					}
					/*
					 * <<<<< listing preview
					 */
					SJB_ListingManager::saveListing($listing);
					SJB_Statistics::addStatistics('addListing', $listing->getListingTypeSID(), $listing->getSID(), false, $extraInfo['featured'], $extraInfo['priority']);
					$contract->incrementPostingsNumber();
					if (isset($_SESSION['tmp_file_storage'])) {
						foreach ($_SESSION['tmp_file_storage'] as $v) {
							SJB_DB::query("UPDATE `listings_pictures` SET `listing_sid` = ?n WHERE `picture_saved_name` = ?s", $listing->getSID(), $v['picture_saved_name']);
							SJB_DB::query("UPDATE `listings_pictures` SET `listing_sid` = ?n WHERE `thumb_saved_name` = ?s", $listing->getSID(), $v['thumb_saved_name']);
						}
						SJB_Session::unsetValue('tmp_file_storage');
					}

					// >>> SJB-1197
					// check temporary uploaded storage for listing uploads and assign it to saved listing
					$formToken           = SJB_Request::getVar('form_token');
					$sessionFilesStorage = SJB_Session::getValue('tmp_uploads_storage');
					$uploadedFields      = SJB_Array::getPath($sessionFilesStorage, $formToken);

					if (!empty($uploadedFields)) {
						foreach ($uploadedFields as $fieldId => $fieldValue) {
							// get field of listing
							$isComplex = false;
							if (strpos($fieldId, ':') !== false) {
								$isComplex = true;
							}

							$tmpUploadedFileId = $fieldValue['file_id'];
							// rename it to real listing field value
							$newFileId = $fieldId . "_" . $listing->getSID();
							SJB_DB::query("UPDATE `uploaded_files` SET `id` = ?s WHERE `id` =?s", $newFileId, $tmpUploadedFileId);

							if ($isComplex) {
								list($parentField, $subField, $complexStep) = explode(':', $fieldId);
								$parentProp  = $listing->getProperty($parentField);
								$parentValue = $parentProp->getValue();

								// look for complex property with current $fieldID and set it to new value of property
								if (!empty($parentValue)) {
									foreach ($parentValue as $id => $value) {
										if ($id == $subField) {
											$parentValue[$id][$complexStep] = $newFileId;
										}
									}
									$listing->setPropertyValue($parentField, $parentValue);
								}
							} else {
								$listing->setPropertyValue($fieldId, $newFileId);
							}

							// unset value from session temporary storage
							$sessionFilesStorage = SJB_Array::unsetValueByPath($sessionFilesStorage, "{$formToken}/{$fieldId}");
						}

						//and remove token key from temporary storage
						$sessionFilesStorage = SJB_Array::unsetValueByPath($sessionFilesStorage, "{$formToken}");
						SJB_Session::setValue('tmp_uploads_storage', $sessionFilesStorage);

						SJB_ListingManager::saveListing($listing);
						$keywords = $listing->getKeywords();
						SJB_ListingManager::updateKeywords($keywords, $listing->getSID());
					}
					// <<< SJB-1197




					if ($isPageLast && !$isPreviewListingRequested) {

						/* delete temp preview listing sid */
						SJB_Session::unsetValue('preview_listing_sid_for_add');

						// Start Event
						$listingSid = $listing->getSID();
						SJB_Event::dispatch('listingSaved', $listingSid);

						// is listing featured by default
						if ($extraInfo['featured'])
							SJB_ListingManager::makeFeaturedBySID($listing->getSID());
						if ($extraInfo['priority'])
							SJB_ListingManager::makePriorityBySID($listing->getSID());

						if (SJB_ListingManager::activateListingBySID($listing->getSID())) {
							SJB_Notifications::sendUserListingActivatedLetter($listing, $listing->getUserSID());
						}

						// notify administrator
						SJB_AdminNotifications::sendAdminListingAddedLetter($listing);

						if (isset($_REQUEST['action_add_pictures']))
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/manage-pictures/?listing_id=" . $listing->getSID());
						else
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/manage-listing/?listing_id=" . $listing->getSID());
					}
					// for listing preview
					elseif ($isPageLast && $isPreviewListingRequested) {
						SJB_Session::setValue('preview_listing_sid_for_add', $listing->getSID());
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/' . strtolower($listingTypeID) . '-preview/' . $listing->getSID() . '/');
					}
					// listing steps (pages)
					else {
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/add-listing/{$listingTypeID}/" . SJB_PostingPagesManager::getNextPage($pageSID) . "/" . $listing->getSID());
					}
				}
				else {
					$listing->deleteProperty('access_list');
					$listing->deleteProperty('contract_id');
					$add_listing_form = new SJB_Form($listing);
					if ($form_submitted)
						$add_listing_form->isDataValid($field_errors);
					$add_listing_form->registerTags($tp);
					$template = isset($_REQUEST['input_template']) ? $_REQUEST['input_template'] : "input_form.tpl";
					$form_fields = $add_listing_form->getFormFieldsInfo();
					$employers_list = SJB_Request::getVar('list_emp_ids', false);
					$employers = array();
					if (is_array($employers_list)) {
						foreach ($employers_list as $emp) {
							$currEmp = SJB_UserManager::getUserInfoBySID($emp);
							$employers[] = array('user_id' => $emp, 'value' => $currEmp['CompanyName']);
						}
						sort($employers);
					}

					$tp->assign('form_token', SJB_Request::getVar('form_token'));


					$tp->assign("account_activated", SJB_Request::getVar('account_activated', ''));
					$tp->assign("listing_id", $tmp_listing_sid);
					$tp->assign("product_sid", $productSID);
					$tp->assign("listing_access_list", $employers);
					$tp->assign("listingTypeID", htmlentities($listingTypeID, ENT_QUOTES, "UTF-8"));
					$tp->assign("field_errors", $field_errors);
					$tp->assign("form_fields", $form_fields);
					$tp->assign("pages", $pages);
					$tp->assign("pageSID", $pageSID);
					$tp->assign("contract", $contract->extra_info);
					$tp->assign("currentPage", SJB_PostingPagesManager::getPageInfoBySID($pageSID));
					$tp->assign("isPageLast", $isPageLast);
					$tp->assign("nextPage", SJB_PostingPagesManager::getNextPage($pageSID));
					$tp->assign("prevPage", SJB_PostingPagesManager::getPrevPage($pageSID));

					$metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
					$tp->assign(
						"METADATA",
						array(
							"form_fields" => $metaDataProvider->getFormFieldsMetadata($form_fields),
						)
					);

					/*
					 * social plugin
					 * only for Resume listing types
					 */
					$aAutoFillData = array('tp' => &$tp, 'listingTypeID' => &$listingTypeID, 'userSID' => $current_user->getSID());
					SJB_Event::dispatch('SocialSynchronizationForm', $aAutoFillData);
					/*
					 * social plugin
					 */

					$tp->display($template);
				}
			}
		}
		else {

			if ($error == 'NO_CONTRACT') {
				SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/products/?page=');
			}

			$tp->assign('listingTypeID', $listingTypeID);
			$tp->assign('error', $error);
			$tp->display('add_listing_error.tpl');
		}

	}
}